<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="Promise 为异步编程提供统一的解决方案，比传统的回调和事件更加合理有效。多重嵌套的回调函数，代码是横向发展，不是纵向发展，容易乱成一团，不便管理，称之为”callback hell”，回调地狱或回调恶梦。Promise就是为了解决这个问题而提出的。它不是新的语法功能，而是一种新的写法，允许将回调函数的横向加载，改成纵向加载。 内容 状态 初始化 then / catch resolve()">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解Promise">
<meta property="og:url" content="http://blog.xiaowuzi.info/2016/10/04/深入理解Promise/index.html">
<meta property="og:site_name" content="小武子博客">
<meta property="og:description" content="Promise 为异步编程提供统一的解决方案，比传统的回调和事件更加合理有效。多重嵌套的回调函数，代码是横向发展，不是纵向发展，容易乱成一团，不便管理，称之为”callback hell”，回调地狱或回调恶梦。Promise就是为了解决这个问题而提出的。它不是新的语法功能，而是一种新的写法，允许将回调函数的横向加载，改成纵向加载。 内容 状态 初始化 then / catch resolve()">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-13T08:10:06.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="深入理解Promise">
<meta name="twitter:description" content="Promise 为异步编程提供统一的解决方案，比传统的回调和事件更加合理有效。多重嵌套的回调函数，代码是横向发展，不是纵向发展，容易乱成一团，不便管理，称之为”callback hell”，回调地狱或回调恶梦。Promise就是为了解决这个问题而提出的。它不是新的语法功能，而是一种新的写法，允许将回调函数的横向加载，改成纵向加载。 内容 状态 初始化 then / catch resolve()">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiaowuzi.info/2016/10/04/深入理解Promise/">





  <title>深入理解Promise | 小武子博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">小武子博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiaowuzi.info/2016/10/04/深入理解Promise/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小武子博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">深入理解Promise</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-10-04T20:51:07+08:00">
                2016-10-04
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/javascript基础/" itemprop="url" rel="index">
                    <span itemprop="name">javascript基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Promise 为异步编程提供统一的解决方案，比传统的回调和事件更加合理有效。<br>多重嵌套的回调函数，代码是横向发展，不是纵向发展，容易乱成一团，不便管理，称之为”callback hell”，回调地狱或回调恶梦。<br>Promise就是为了解决这个问题而提出的。它不是新的语法功能，而是一种新的写法，允许将回调函数的横向加载，改成纵向加载。</p>
<h2 id="内容"><a href="#内容" class="headerlink" title="内容"></a>内容</h2><ul>
<li>状态</li>
<li>初始化</li>
<li>then / catch</li>
<li>resolve() / reject()</li>
<li>all() / race()</li>
<li>done / finally</li>
</ul>
<h2 id="状态"><a href="#状态" class="headerlink" title="状态"></a>状态</h2><p>Promise的三个状态：Pending 进行中 / Resolved 已成功 / Rejected 已失败</p>
<p>状态改变方式:</p>
<p>Pending =&gt; Resolved</p>
<p>Pending =&gt; Rejected</p>
<p>将异步操作以同步的操作编程表达出来，避免了层层嵌套的回调函数。</p>
<h2 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h2><ul>
<li>一旦新建它就会立即执行，无法中途取消</li>
<li>如果不设置回调函数，Promise内部抛出的错误，不会反应到外部</li>
<li>当处于Pending状态时，无法得知目前进展到哪一个阶段（刚刚开始还是即将完成）<a id="more"></a>
<h2 id="实例化"><a href="#实例化" class="headerlink" title="实例化"></a>实例化</h2></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var promise = new Promise(function(resolve, reject) &#123;</span><br><span class="line">  // ... some code</span><br><span class="line">  if (/* 异步操作成功 */)&#123;</span><br><span class="line">    resolve(value);</span><br><span class="line">  &#125; else &#123;</span><br><span class="line">    reject(error);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<ul>
<li>Promise接收一个函数作为参数，函数的两个参数resolve, reject是两个函数，用于对promise对象的状态改变</li>
<li>resove 将未完成变成已完成 pending =&gt; resolved</li>
<li>reject 将未完成变成已失败 pending =&gt; rejected</li>
</ul>
<h2 id="then-与-catch"><a href="#then-与-catch" class="headerlink" title="then 与 catch"></a>then 与 catch</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Promise.prototype.then()</span><br></pre></td></tr></table></figure>
<p>then方法接收两个函数参数，第一个表示resove 已成功的回调，第二个表示reject 已失败的回调</p>
<h2 id="用法"><a href="#用法" class="headerlink" title="用法"></a>用法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var p = new Promise(function(resolve, reject)&#123; ... &#125;)</span><br><span class="line">p.then(function()&#123;&#125;, function()&#123;&#125;)</span><br><span class="line">p.then().catch();</span><br></pre></td></tr></table></figure>
<h2 id="异步加载图片"><a href="#异步加载图片" class="headerlink" title="异步加载图片"></a>异步加载图片</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">unction loadImageAsync(url) &#123;</span><br><span class="line">  return new Promise(function(resolve, reject) &#123;</span><br><span class="line">    var image = new Image();</span><br><span class="line">    image.onload = function() &#123;</span><br><span class="line">      resolve(image);</span><br><span class="line">    &#125;;</span><br><span class="line">    image.onerror = function() &#123;</span><br><span class="line">      reject(new Error(&apos;Could not load image at &apos; + url));</span><br><span class="line">    &#125;;</span><br><span class="line">    image.src = url;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line">loadImagesAsync(&apos;//img.static.com/xxx.jpg&apos;).then(function(img)&#123;</span><br><span class="line">	//加载成功 显示图片</span><br><span class="line">&#125;, function(err)&#123;</span><br><span class="line">	//加载失败 提示失败</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="异步加载数据"><a href="#异步加载数据" class="headerlink" title="异步加载数据"></a>异步加载数据</h2><p>使用promise包装一个异步请，返回一个promise对象，使用then和catch的方式对返回结果进行处理</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">var getJSON = function(url)&#123;</span><br><span class="line">	return new Promise((resolve, reject)=&gt;&#123;</span><br><span class="line">		var client = new XMLHttpRequest();</span><br><span class="line">		client.open(&apos;GET&apos;, url);</span><br><span class="line">		client.onreadystatechange = callback;</span><br><span class="line">		client.send();</span><br><span class="line">		function callback()&#123;</span><br><span class="line">			if(this.readyState !== 4) return;</span><br><span class="line">			if(this.status === 200)&#123;</span><br><span class="line">				resolve(this.response)</span><br><span class="line">			&#125;else&#123;</span><br><span class="line">				reject(new Error(this.statusText))</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;)</span><br><span class="line">&#125;</span><br><span class="line">getJSON(&apos;/api/getList&apos;).then(function(data)&#123;</span><br><span class="line">	//获取请求的数据</span><br><span class="line">&#125;, function(err)&#123;</span><br><span class="line">	//请求失败错误处理</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="执行顺序"><a href="#执行顺序" class="headerlink" title="执行顺序"></a>执行顺序</h2><p>Promise 在实例化的时候就会执行，是一条执行语句</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var p1 = new Promise(function (resolve, reject) &#123;</span><br><span class="line">	console.log(&apos;p1 start&apos;)</span><br><span class="line">&#125;)</span><br><span class="line">var p2 = new Promise(function (resolve, reject) &#123;</span><br><span class="line">	console.log(&apos;p2 start&apos;)</span><br><span class="line">&#125;)</span><br><span class="line">// 输出：</span><br><span class="line">// p1 start</span><br><span class="line">// p2 start</span><br></pre></td></tr></table></figure>
<h2 id="嵌套"><a href="#嵌套" class="headerlink" title="嵌套"></a>嵌套</h2><p>Promise 嵌套，状态改变由最内层的promise对象决定</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">var st, res = true;</span><br><span class="line">var p1 = ()=&gt; new Promise(function (resolve, reject) &#123;</span><br><span class="line">	console.log(&apos;p1 start&apos;)</span><br><span class="line">  setTimeout(() =&gt; &#123;</span><br><span class="line">  	if(res)&#123;</span><br><span class="line">  		resolve(Date.now() - st +&apos; P1 success&apos;)</span><br><span class="line">  	&#125;else&#123;</span><br><span class="line">  		reject(new Error(Date.now() - st +&apos; P1 fail&apos;));</span><br><span class="line">  	&#125;</span><br><span class="line">  &#125;, 3000)</span><br><span class="line">&#125;)</span><br><span class="line">var p2 = ()=&gt; new Promise(function (resolve, reject) &#123;</span><br><span class="line">	st = Date.now()</span><br><span class="line">	console.log(&apos;p2 start&apos;)</span><br><span class="line">  setTimeout(() =&gt; &#123;</span><br><span class="line">  	if(res)&#123;</span><br><span class="line">  		resolve(p1())</span><br><span class="line">  	&#125;else&#123;</span><br><span class="line">  		reject(new Error(Date.now() - st + &apos; P2 fail&apos;));</span><br><span class="line">  	&#125;</span><br><span class="line">  &#125;, 1000)</span><br><span class="line">&#125;)</span><br><span class="line">p2()</span><br><span class="line">	.then(result =&gt; console.log(result))</span><br><span class="line">	.catch(error =&gt; console.log(error.message))</span><br><span class="line">// 输出：</span><br><span class="line">// p2 start</span><br><span class="line">// Promise &#123;[[PromiseStatus]]: &quot;pending&quot;, [[PromiseValue]]: undefined&#125;</span><br><span class="line">// p1 start</span><br><span class="line">// 4002 P1 success</span><br></pre></td></tr></table></figure>
<h2 id="then的调用"><a href="#then的调用" class="headerlink" title="then的调用"></a>then的调用</h2><p>前一个then的返回结果，可以再后一then的回调中获取</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">var p3 = ()=&gt; new Promise((resolve, reject)=&gt;&#123;</span><br><span class="line">	resolve(&apos;&#123;&quot;name&quot;:&quot;jack&quot;, &quot;age&quot;:28&#125;&apos;)</span><br><span class="line">&#125;);</span><br><span class="line">p3()</span><br><span class="line">	.then(res =&gt; JSON.parse(res))</span><br><span class="line">	.then(data =&gt; Object.assign(data, &#123;name:&apos;rose&apos;&#125;))</span><br><span class="line">	.then(data =&gt; console.log(data))</span><br><span class="line">// 输出：&#123;name: &quot;rose&quot;, age: 28&#125;</span><br><span class="line">var p4 = ()=&gt;&#123;</span><br><span class="line">	var st = Date.now();</span><br><span class="line">	getJSON(&apos;data1.json?delay=1000&apos;)</span><br><span class="line">		.then(data =&gt; &#123;</span><br><span class="line">			console.log(Date.now()-st, data);</span><br><span class="line">			return getJSON(&apos;data2.json?delay=2000&apos;)</span><br><span class="line">		&#125;)</span><br><span class="line">		.then(data =&gt; console.log(Date.now()-st, data))</span><br><span class="line">		.catch(err =&gt; console.log(err.message))</span><br><span class="line">&#125;</span><br><span class="line">p4();</span><br><span class="line">// 1016 &quot;&#123;&quot;status&quot;:&quot;0&quot;&#125;&quot;</span><br><span class="line">// 3028 &quot;&#123;&quot;status&quot;:&quot;1&quot;&#125;&quot;</span><br></pre></td></tr></table></figure>
<h2 id="Catch"><a href="#Catch" class="headerlink" title="Catch"></a>Catch</h2><p><code>Promise.prototype.catch</code></p>
<p>p.catch()用于处理promise中rejected状态的回调，与p.then(resolveFn, rejectFn)中 rejectFn的作用相同</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">var p = new Promise(function(resolve, reject)&#123; ... &#125;);</span><br><span class="line">p.then(function()&#123;&#125;, function()&#123;&#125;);</span><br><span class="line">等同于</span><br><span class="line">p.then(function()&#123;&#125;).catch(function()&#123;&#125;);</span><br></pre></td></tr></table></figure>
<p>reject(‘error’) 与 throw new Error(‘…’) 都能被catch捕获</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">new Promise((resolve, reject) =&gt; &#123; </span><br><span class="line">	throw new Error(&apos;some error1&apos;);</span><br><span class="line">&#125;).catch(err =&gt;  console.log(err.message))</span><br><span class="line">// 等同于</span><br><span class="line">new Promise((resolve, reject) =&gt; &#123; </span><br><span class="line">	reject(&apos;some error2&apos;)</span><br><span class="line">&#125;).catch(err =&gt; console.log(err))</span><br><span class="line">//输出</span><br><span class="line">// some error1</span><br><span class="line">// some error2</span><br></pre></td></tr></table></figure>
<h2 id="异常捕获"><a href="#异常捕获" class="headerlink" title="异常捕获"></a>异常捕获</h2><p>promise对象的错误，具有 冒泡 性质，会一直向后传递，直到被捕获</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">new Promise((resolve, reject) =&gt; &#123; </span><br><span class="line">	throw new Error(&apos;some error1&apos;);</span><br><span class="line">&#125;).then().then().then().catch(err =&gt;  console.log(err.message))</span><br></pre></td></tr></table></figure>
<p>推荐使用 catch 代替then(null, rejectFn)中的rejectFn</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">// bad</span><br><span class="line">new Promise(function(resolve, reject)&#123;&#125;).then(resolveFn, rejectFn)</span><br><span class="line">// good</span><br><span class="line">new Promise(function(resolve, reject)&#123;</span><br><span class="line">&#125;).then(resoveFn).catch(rejectFn)</span><br></pre></td></tr></table></figure>
<p>原因是：catch可以捕获前面then函数返回的错误信息，也更接近同步的写法</p>
<p>promise对象的错误，如果不指定catch来捕获错误，那么错误不会被传递到外层代码（chrome浏览器例外）</p>
<p>catch 返回的是一个promise对象，后面同样可以调用then、catch<br>前面的catch中错误可以被后面的catch捕获</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Promise.reject(&apos;err1&apos;)</span><br><span class="line">	.catch(err =&gt; console.log(err))</span><br><span class="line">	.then(() =&gt; console.log(&apos;success&apos;));</span><br><span class="line">// err1</span><br><span class="line">// success</span><br><span class="line">Promise.reject(&apos;err1&apos;)</span><br><span class="line">	.catch(err =&gt; &#123;console.log(err); x+1&#125;)</span><br><span class="line">	.then(() =&gt; console.log(&apos;success&apos;));</span><br><span class="line">Promise.reject(&apos;err1&apos;)</span><br><span class="line">	.catch(err =&gt; &#123;console.log(err); x+1&#125;)</span><br><span class="line">	.catch(err =&gt; console.log(err.message));</span><br><span class="line">// err1</span><br><span class="line">// x is not defined</span><br><span class="line">Promise.resolve(&apos;success1&apos;)</span><br><span class="line">	.catch(err =&gt; console.log(err))</span><br><span class="line">	.then(msg =&gt; console.log(msg));</span><br><span class="line">// success1</span><br></pre></td></tr></table></figure>
<h2 id="all-与-race"><a href="#all-与-race" class="headerlink" title="all 与 race"></a>all 与 race</h2><p><code>Promise.all([])</code>与<code>Promise.race([])</code></p>
<ul>
<li>接收一个数组做为参数，参数中的每个元素为promise实例，</li>
<li>如果元素不是promise实例，则会调用Promise.resolve()转换为promise的实例</li>
<li>将多个promise对象包装为一个新的promise对象</li>
</ul>
<h2 id="Promise-all"><a href="#Promise-all" class="headerlink" title="Promise.all()"></a>Promise.all()</h2><ul>
<li>当p1、p2、p3的状态全部为resolved时，才能将p的状态改为resolved</li>
<li>当p1、p2、p3其中一个状态变成rejected时，就会将p的状态变成rejected</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var p = Promise.all([Promise.resolve(&apos;1&apos;), Promise.resolve(&apos;2&apos;), </span><br><span class="line">Promise.resolve(&apos;3&apos;)]);</span><br><span class="line">p.then(data =&gt; console.log(data)) //[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;]</span><br><span class="line">var p1 = Promise.all([Promise.resolve(&apos;1&apos;), Promise.reject(&apos;2&apos;), </span><br><span class="line">Promise.resolve(&apos;3&apos;)]);</span><br><span class="line">p1.then(data =&gt; console.log(data)).catch(err =&gt; console.log(err)) // 2</span><br></pre></td></tr></table></figure>
<h2 id="Promise-race"><a href="#Promise-race" class="headerlink" title="Promise.race()"></a>Promise.race()</h2><p>当p1、p2、p3其中一个状态发生改变时，就相应的触发p的状态发生变化</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var p1 = new Promise((resolve, reject)=&gt;setTimeout(()=&gt;resolve(&apos;p1 success&apos;), 2000))</span><br><span class="line">var p2 = new Promise((resolve, reject)=&gt;setTimeout(()=&gt;reject(&apos;p2 error&apos;), 1000))</span><br><span class="line">var p3 = new Promise((resolve, reject)=&gt;setTimeout(()=&gt;resolve(&apos;p3 success&apos;), 3000))</span><br><span class="line">var p = Promise.race([p1, p2, p3]);</span><br><span class="line">p.then(data =&gt; console.log(data)).catch(err =&gt; console.log(err)); //p2 error</span><br></pre></td></tr></table></figure>
<h2 id="Promise-resolve-与-Promise-reject"><a href="#Promise-resolve-与-Promise-reject" class="headerlink" title="Promise.resolve() 与 Promise.reject()"></a>Promise.resolve() 与 Promise.reject()</h2><p>将普通对象转换为Promise对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Promise.resolve(&apos;foo&apos;)</span><br><span class="line">// 等价于</span><br><span class="line">new Promise(resolve =&gt; resolve(&apos;foo&apos;))</span><br></pre></td></tr></table></figure>
<p>Pormise.resolve()的四种参数</p>
<ol>
<li>promise实例，则会返回这个实例</li>
<li>含有then方法的对象，则先执行then方法，再返回promise对象</li>
<li>参数是基本类型的值，数据或字符串，则直接resolve这个值</li>
<li>不带参数执行，则返回一个resolved的promise对象</li>
</ol>
<p>Promise.reject()与之类似</p>
<p>Promise.reject()返回一个rejected的promise对象</p>
<h2 id="defer"><a href="#defer" class="headerlink" title="defer"></a>defer</h2><p>Promise.defer 延迟对象，返回一个Promise的实例、resolve、reject方法</p>
<p>defer风格的Promise</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function doSth() &#123;</span><br><span class="line">    var defer = Promise.defer();</span><br><span class="line">    setTimeout(function()&#123;</span><br><span class="line">        defer.resolve();</span><br><span class="line">    &#125;,1000)</span><br><span class="line">    return defer.promise;</span><br><span class="line">&#125;</span><br><span class="line">等同于</span><br><span class="line">doSth = ()=&gt; new Promise((resolve, reject) =&gt; setTimeout( ()=&gt; resolve(&apos;success&apos;), 1000) )</span><br></pre></td></tr></table></figure>
<h2 id="done-与-finally"><a href="#done-与-finally" class="headerlink" title="done 与 finally"></a>done 与 finally</h2><p>添加两个ES6的Promise扩展方法 done()、finally()</p>
<h2 id="done"><a href="#done" class="headerlink" title="done"></a>done</h2><p>done方法: 用于任何可能出现的错误，并向全局抛出。</p>
<p>由于Promise的错误不会冒泡到全局，如果在promise对象的最终then或catch方法中有报错，则无法捕获到。</p>
<p>done()用于promise()尾端调用，可捕获前面未捕获的错误</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">Promise.prototype.done = function(onResolved, onRejected)&#123;</span><br><span class="line">	this</span><br><span class="line">		.then(onResolved, onRejected)</span><br><span class="line">		.catch(function(err)&#123;</span><br><span class="line">			setTimeout(() =&gt; &#123; throw err&#125;, 0); //抛出一个全局错误</span><br><span class="line">		&#125;)</span><br><span class="line">&#125;</span><br><span class="line">var p = ()=&gt;new Promise((resolve, reject) =&gt; resolve(&apos;success&apos;));</span><br><span class="line">p()</span><br><span class="line">  .then(data =&gt; &#123;console.log(data); x+1;&#125;)</span><br><span class="line">  .catch(err =&gt; &#123;console.log(err.message); y+2;&#125;)</span><br><span class="line">  .then(data =&gt; console.log(data))</span><br><span class="line">  .done();</span><br></pre></td></tr></table></figure>
<h2 id="finally"><a href="#finally" class="headerlink" title="finally"></a>finally</h2><p>finally方法：用于指定不管Promise对象最后状态如何，都会执行的操作</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">Promise.prototype.finally = function (callback) &#123;</span><br><span class="line">	&apos;use strict&apos;;</span><br><span class="line">	let P = this.constructor;</span><br><span class="line">	return this.then(</span><br><span class="line">		value =&gt; P.resolve(callback(value)),</span><br><span class="line">		err =&gt; P.resolve(callback(err))</span><br><span class="line">	);</span><br><span class="line">&#125;;</span><br><span class="line">var p = () =&gt; new Promise((resolve, reject) =&gt; resolve(&apos;success&apos;));</span><br><span class="line">p()</span><br><span class="line">	.then(data =&gt; &#123;console.log(data); x+1;&#125;)</span><br><span class="line">	.catch(err =&gt; &#123;console.log(err.message); y+2;&#125;)</span><br><span class="line">	.then(data =&gt; console.log(data))</span><br><span class="line">	.finally(data =&gt; console.log(data));</span><br></pre></td></tr></table></figure>
<p>参考资料：</p>
<p><a href="http://coderlt.coding.me/2016/07/17/ES6-promise/" target="_blank" rel="noopener">ES6笔记 - Promise模式</a></p>
<p><a href="http://es6.ruanyifeng.com/#docs/promise" target="_blank" rel="noopener">Promise对象</a></p>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center">
  <div>Donate comment here</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Tony 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Tony 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/07/08/http2/" rel="next" title="http2">
                <i class="fa fa-chevron-left"></i> http2
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/05/深入理解 Promise (中)/" rel="prev" title="深入理解 Promise (中)">
                深入理解 Promise (中) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">65</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#内容"><span class="nav-number">1.</span> <span class="nav-text">内容</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态"><span class="nav-number">2.</span> <span class="nav-text">状态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#缺点"><span class="nav-number">3.</span> <span class="nav-text">缺点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实例化"><span class="nav-number">4.</span> <span class="nav-text">实例化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#then-与-catch"><span class="nav-number">5.</span> <span class="nav-text">then 与 catch</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#用法"><span class="nav-number">6.</span> <span class="nav-text">用法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异步加载图片"><span class="nav-number">7.</span> <span class="nav-text">异步加载图片</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异步加载数据"><span class="nav-number">8.</span> <span class="nav-text">异步加载数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#执行顺序"><span class="nav-number">9.</span> <span class="nav-text">执行顺序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#嵌套"><span class="nav-number">10.</span> <span class="nav-text">嵌套</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#then的调用"><span class="nav-number">11.</span> <span class="nav-text">then的调用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Catch"><span class="nav-number">12.</span> <span class="nav-text">Catch</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异常捕获"><span class="nav-number">13.</span> <span class="nav-text">异常捕获</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#all-与-race"><span class="nav-number">14.</span> <span class="nav-text">all 与 race</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-all"><span class="nav-number">15.</span> <span class="nav-text">Promise.all()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-race"><span class="nav-number">16.</span> <span class="nav-text">Promise.race()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-resolve-与-Promise-reject"><span class="nav-number">17.</span> <span class="nav-text">Promise.resolve() 与 Promise.reject()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#defer"><span class="nav-number">18.</span> <span class="nav-text">defer</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#done-与-finally"><span class="nav-number">19.</span> <span class="nav-text">done 与 finally</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#done"><span class="nav-number">20.</span> <span class="nav-text">done</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#finally"><span class="nav-number">21.</span> <span class="nav-text">finally</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>